<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的订单 - 用户中心</title>
    <link rel="stylesheet" type="text/css" href="./css/webbase.css"/>
    <link rel="stylesheet" type="text/css" href="./css/top-nav-optimized.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.8;
            color: #333;
            background-color: #f5f7fa;
            min-height: 100vh;
        }

        /* 导航栏样式（与用户中心保持一致） */
        .nav-logo i {
            color: #3498db;
        }

        .nav-links {
            display: flex;
            list-style: none;
            gap: 25px;
        }

        .nav-links li a {
            color: white;
            text-decoration: none;
            font-size: 0.95rem;
            font-weight: 500;
            padding: 5px 0;
            position: relative;
            transition: color 0.3s ease;
        }

        .nav-links li a:hover {
            color: #3498db;
        }

        .nav-links li a::after {
            content: '';
            position: absolute;
            width: 0;
            height: 2px;
            bottom: 0;
            left: 0;
            background-color: #3498db;
            transition: width 0.3s ease;
        }

        .nav-links li a:hover::after {
            width: 100%;
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-menu .icon-btn {
            background: none;
            border: none;
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
            transition: color 0.3s ease;
        }

        .user-menu .icon-btn:hover {
            color: #3498db;
        }

        /* 主内容区样式 */
        .container {
            max-width: 1200px;
            margin: 30px auto;
            padding: 0 20px;
        }

        .page-title {
            color: #2c3e50;
            margin: 20px 0 30px;
            font-size: 1.8rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #e1e5eb;
            padding-bottom: 15px;
        }

        .page-title i {
            color: #ff6700;
            margin-right: 10px;
            font-size: 1.5rem;
        }

        /* 订单筛选区 */
        .filter-bar {
            background: white;
            border-radius: 12px;
            padding: 15px 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .filter-options {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }

        .filter-btn {
            padding: 6px 16px;
            border-radius: 20px;
            border: 1px solid #e0e0e0;
            background: white;
            color: #666;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .filter-btn.active {
            background: #ff6700;
            color: white;
            border-color: #ff6700;
        }

        .filter-btn:hover:not(.active) {
            border-color: #ff6700;
            color: #ff6700;
        }

        /* 订单列表样式 */
        .order-list {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .order-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .order-header {
            padding: 15px 20px;
            border-bottom: 1px solid #f0f2f5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .order-id {
            font-size: 0.95rem;
            color: #666;
        }

        .order-status {
            font-weight: 500;
        }

        /* 订单状态标签样式 */
        .status-1 { color: #ff9800; } /* 未付款 */
        .status-2 { color: #2196f3; } /* 已付款,未发货 */
        .status-3 { color: #3f51b5; } /* 已发货,未确认 */
        .status-4 { color: #4caf50; } /* 确认收货，交易成功 */
        .status-5 { color: #f44336; } /* 交易取消 */
        .status-6 { color: #9c27b0; } /* 已评价 */

        /* 订单商品列表 */
        .order-items {
            padding: 15px 20px;
        }

        .order-item {
            display: flex;
            gap: 15px;
            padding: 10px 0;
            border-bottom: 1px solid #f9f9f9;
        }

        .item-img {
            width: 80px;
            height: 80px;
            border-radius: 8px;
            overflow: hidden;
            flex-shrink: 0;
        }

        .item-img img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .item-info {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .item-name {
            font-size: 0.95rem;
            margin-bottom: 5px;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
        }

        .item-attr {
            font-size: 0.85rem;
            color: #999;
            margin-bottom: 5px;
        }

        .item-price {
            font-size: 0.9rem;
            color: #e63946;
        }

        /* 订单金额与操作 */
        .order-footer {
            padding: 15px 20px;
            border-top: 1px solid #f0f2f5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .order-total {
            font-size: 0.95rem;
        }

        .total-price {
            font-size: 1.1rem;
            font-weight: 600;
            color: #e63946;
        }

        .order-actions {
            display: flex;
            gap: 10px;
        }

        .action-btn {
            padding: 6px 16px;
            border-radius: 8px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1px solid #ff6700;
            background: transparent;
            color: #ff6700;
        }

        .action-btn:hover {
            background: #ff6700;
            color: white;
        }

        .action-btn.primary {
            background: #ff6700;
            color: white;
        }

        .action-btn.primary:hover {
            background: #e05a00;
        }

        /* 空订单状态 */
        .empty-order {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .empty-icon {
            font-size: 4rem;
            color: #e0e0e0;
            margin-bottom: 20px;
        }

        .empty-text {
            color: #999;
            margin-bottom: 20px;
            font-size: 1.1rem;
        }

        .go-shopping {
            padding: 10px 20px;
            background: #ff6700;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .go-shopping:hover {
            background: #e05a00;
        }

        /* 分页控件 */
        .pagination {
            display: flex;
            justify-content: center;
            margin: 40px 0;
            gap: 8px;
        }

        .page-btn {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            border: 1px solid #e0e0e0;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .page-btn:hover:not(.active):not(.disabled) {
            border-color: #ff6700;
            color: #ff6700;
        }

        .page-btn.active {
            background: #ff6700;
            color: white;
            border-color: #ff6700;
        }

        .page-btn.disabled {
            color: #ccc;
            cursor: not-allowed;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .nav-links {
                display: none;
            }

            .page-title {
                font-size: 1.5rem;
            }

            .filter-options {
                gap: 8px;
            }

            .filter-btn {
                padding: 5px 12px;
                font-size: 0.85rem;
            }

            .order-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 5px;
            }

            .order-footer {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .order-actions {
                width: 100%;
                justify-content: space-between;
            }

            .action-btn {
                flex: 1;
                text-align: center;
                padding: 8px 0;
                font-size: 0.85rem;
            }
        }
    </style>
</head>
<div id="app">
    <top></top>
</div>
<body>
<div class="container">
    <h1 class="page-title"><i class="fas fa-box"></i>我的订单</h1>

    <!-- 订单筛选 -->
    <div class="filter-bar">
        <div class="filter-options">
            <button class="filter-btn active" data-status="all">全部订单</button>
            <button class="filter-btn" data-status="1">未付款</button>
            <button class="filter-btn" data-status="2">已付款，未发货</button>
            <button class="filter-btn" data-status="3">已发货，未确认</button>
            <button class="filter-btn" data-status="4">交易成功</button>
            <button class="filter-btn" data-status="5">已取消</button>
            <button class="filter-btn" data-status="6">已评价</button>
        </div>
    </div>

    <!-- 订单列表 -->
    <div class="order-list" id="orderList">
        <!-- 订单卡片示例（实际数据通过JS渲染） -->
        <!-- <div class="order-card">
            <div class="order-header">
                <div class="order-id">订单编号：20231023123456789</div>
                <div class="order-status status-2">已付款，未发货</div>
            </div>
            <div class="order-items">
                <div class="order-item">
                    <div class="item-img">
                        <img src="https://img.yzcdn.cn/vant/example/goods-1.jpg" alt="商品图片">
                    </div>
                    <div class="item-info">
                        <div class="item-name">示例商品名称，这是一个比较长的商品名称测试</div>
                        <div class="item-attr">颜色：红色 / 尺寸：XL</div>
                        <div class="item-price">¥99.00 x 1</div>
                    </div>
                </div>
            </div>
            <div class="order-footer">
                <div class="order-total">
                    共 1 件商品 合计：<span class="total-price">¥99.00</span>（含运费）
                </div>
                <div class="order-actions">
                    <button class="action-btn">查看详情</button>
                    <button class="action-btn primary">提醒发货</button>
                </div>
            </div>
        </div> -->
    </div>

    <!-- 空订单状态 -->
    <div class="empty-order" id="emptyOrder" style="display: none;">
        <div class="empty-icon">
            <i class="fas fa-box-open"></i>
        </div>
        <div class="empty-text">暂无相关订单</div>
        <button class="go-shopping" onclick="window.location.href='/index.html'">
            <i class="fas fa-shopping-bag"></i> 去购物
        </button>
    </div>

    <!-- 分页 -->
    <div class="pagination" id="pagination">
        <button class="page-btn disabled" id="prevPage">
            <i class="fas fa-angle-left"></i>
        </button>
        <button class="page-btn active">1</button>
        <button class="page-btn">2</button>
        <button class="page-btn">3</button>
        <button class="page-btn" id="nextPage">
            <i class="fas fa-angle-right"></i>
        </button>
    </div>
</div>

<script src="./js/axios.min.js"></script>
<script src="./js/common.js"></script>
<script src="./js/vue.js"></script>
<script src="./js/top.js"></script>

<script>
    // 订单状态文本映射
    const statusMap = {
        1: '未付款',
        2: '已付款，未发货',
        3: '已发货，未确认',
        4: '交易成功',
        5: '已取消',
        6: '已评价'
    };

    // 当前筛选状态和分页信息
    let currentStatus = 'all';
    let currentPage = 1;
    const pageSize = 5;

    // 页面加载时初始化
    window.onload = function() {
        // 检查登录状态
        if (!util.isLogin()) {
            util.store.set("return-url", location.href);
            location.href = "login.html";
            return;
        }

        // 加载订单数据
        fetchOrders();

        // 绑定筛选按钮事件
        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                // 更新活跃状态
                document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
                this.classList.add('active');

                // 更新筛选状态并重新加载数据
                currentStatus = this.dataset.status;
                currentPage = 1;
                fetchOrders();
            });
        });

        // 绑定分页按钮事件
        document.getElementById('prevPage').addEventListener('click', function() {
            if (currentPage > 1) {
                currentPage--;
                fetchOrders();
            }
        });

        document.getElementById('nextPage').addEventListener('click', function() {
            currentPage++;
            fetchOrders();
        });
    };

    // 获取订单数据（修改后）
    function fetchOrders() {
        // 构建请求参数
        const params = {
            page: currentPage,
            size: pageSize
        };

        // 如果不是筛选全部，添加状态参数
        if (currentStatus !== 'all') {
            params.status = currentStatus;
        }

        // 调用后端接口获取订单列表
        axios.get('http://localhost:8080/orders/myOrders', { params })
            .then(response => {
                const orders = response.data; // 后端数据在 data 数组中
                const totalPages = Math.ceil(orders.length / pageSize); // 临时计算总页数（建议后端返回真实总页数）
                renderOrders(orders);
                updatePagination(totalPages);

                // 显示空订单状态或订单列表
                document.getElementById('orderList').style.display = orders.length > 0 ? 'flex' : 'none';
                document.getElementById('emptyOrder').style.display = orders.length > 0 ? 'none' : 'block';
            })
            .catch(error => {
                console.error('获取订单失败:', error);
                alert('获取订单失败，请稍后重试');
            });
    }

    // 渲染订单列表（完全修复）
    function renderOrders(orders) {
        const orderListEl = document.getElementById('orderList');
        orderListEl.innerHTML = '';

        orders.forEach(order => {
            // 转换金额单位（分 -> 元），适配后端 totalFee 字段
            const totalFee = (order.totalFee / 100).toFixed(2);
            // 动态计算商品数量（若后端返回items则取长度，否则默认1）
            const itemCount = order.items && order.items.length > 0 ? order.items.length : 1;

            // 创建订单卡片
            const orderCard = document.createElement('div');
            orderCard.className = 'order-card';

            // 格式化时间，适配后端 createTime 字段
            const createTime = formatDate(order.createTime);

            // 订单卡片内容（修复所有问题）
            orderCard.innerHTML = `
                <div class="order-header">
                    <div class="order-id">订单编号：${order.id}<br>创建时间：${createTime}</div>
                    <div class="order-status status-${order.status}">${statusMap[order.status]}</div>
                </div>

                <div class="order-footer">
                    <div class="order-total">
                        共 ${itemCount} 件商品 合计：<span class="total-price">¥${totalFee}</span>
                        <br>支付方式：${getPaymentType(order.paymentType)}
                    </div>
                    <div class="order-actions">
                        ${renderOrderActions(order.status, order.id)}
                    </div>
                </div>
            `;

            orderListEl.appendChild(orderCard);
        });
    }

    // 渲染订单商品列表（修复未定义变量问题）
    function renderOrderItems(items, totalFee) {
        if (!items || items.length === 0) {
            return `

            `;
        }

        // 有商品数据时，正常渲染（适配后端可能返回的商品字段）
        return items.map(item => {
            // 商品单价适配（若后端返回item.price则转换，否则用订单总金额均分）
            const itemPrice = item.price ? (item.price / 100).toFixed(2) : (totalFee / items.length).toFixed(2);
            return `

        `;
        }).join('');
    }

    // 支付类型映射（保持不变）
    function getPaymentType(type) {
        const paymentMap = {
            1: '支付宝',
            2: '微信',
            3: '扣减余额'
        };
        return paymentMap[type] || '未知支付方式';
    }



    // 根据订单状态渲染操作按钮（修复所有按钮的ID传递）
    function renderOrderActions(status, orderId) {
        // 关键：给 orderId 加单引号，作为字符串传递，避免超长数字精度丢失
        const orderIdStr = `'${orderId}'`;

        switch(status) {
            case 1: // 未付款
                return `
                    <button class="action-btn" onclick="viewOrderDetail(${orderIdStr})">查看详情</button>
                    <button class="action-btn" onclick="cancelOrder(${orderIdStr})">取消订单</button>
                    <button class="action-btn primary" onclick="payOrder(${orderIdStr})">去付款</button>
                `;
            case 2: // 已付款，未发货
                return `
                    <button class="action-btn" onclick="viewOrderDetail(${orderIdStr})">查看详情</button>
                    <button class="action-btn primary" onclick="remindShip(${orderIdStr})">提醒发货</button>
                `;
            case 3: // 已发货，未确认
                return `
                    <button class="action-btn" onclick="viewLogistics(${orderIdStr})">查看物流</button>
                    <button class="action-btn primary" onclick="confirmReceipt(${orderIdStr})">确认收货</button>
                `;
            case 4: // 交易成功
                return `
                    <button class="action-btn" onclick="viewOrderDetail(${orderIdStr})">查看详情</button>
                    <button class="action-btn primary" onclick="gotoComment(${orderIdStr})">去评价</button>
                `;
            case 5: // 已取消
                return `
                    <button class="action-btn" onclick="viewOrderDetail(${orderIdStr})">查看详情</button>
                    <button class="action-btn primary" onclick="deleteOrder(${orderIdStr})">删除订单</button>
                `;
            case 6: // 已评价
                return `
                    <button class="action-btn" onclick="viewOrderDetail(${orderIdStr})">查看详情</button>
                    <button class="action-btn" onclick="viewComment(${orderIdStr})">查看评价</button>
                `;
            default:
                return `<button class="action-btn" onclick="viewOrderDetail(${orderIdStr})">查看详情</button>`;
        }
    }

    // 更新分页控件
    function updatePagination(totalPages) {
        const paginationEl = document.getElementById('pagination');
        const prevBtn = document.getElementById('prevPage');
        const nextBtn = document.getElementById('nextPage');

        // 更新前后页按钮状态
        prevBtn.classList.toggle('disabled', currentPage === 1);
        nextBtn.classList.toggle('disabled', currentPage >= totalPages);

        // 简单分页逻辑（实际项目中可根据需求优化）
        document.querySelectorAll('.page-btn:not(#prevPage):not(#nextPage)').forEach(btn => {
            btn.remove();
        });

        for (let i = 1; i <= Math.min(totalPages, 5); i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `page-btn ${i === currentPage ? 'active' : ''}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', () => {
                currentPage = i;
                fetchOrders();
            });
            nextBtn.parentNode.insertBefore(pageBtn, nextBtn);
        }
    }

    // 日期格式化工具（保持不变，确保兼容后端时间格式）
    function formatDate(dateStr) {
        if (!dateStr) return '';
        const date = new Date(dateStr);
        // 修复IOS系统下日期解析问题（后端时间格式是ISO8601，部分浏览器需兼容）
        if (isNaN(date.getTime())) {
            dateStr = dateStr.replace('T', ' ');
            return new Date(dateStr).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // 订单操作函数（仅示例，实际需根据后端接口实现）
    function payOrder(orderId) {
        alert(`跳转到支付页面，订单ID：${orderId}`);
        // 实际项目中应跳转到支付页面或调用支付接口
    }

    function cancelOrder(orderId) {
        if (confirm('确定要取消该订单吗？')) {
            axios.post(`http://localhost:8080/orders/${orderId}/cancel`)
                .then(() => {
                    alert('订单已取消');
                    fetchOrders();
                })
                .catch(error => {
                    console.error('取消订单失败:', error);
                    alert('取消订单失败，请稍后重试');
                });
        }
    }

    function confirmReceipt(orderId) {
        if (confirm('确定已收到商品吗？')) {
            axios.post(`http://localhost:8080/orders/${orderId}/confirm`)
                .then(() => {
                    alert('已确认收货');
                    fetchOrders();
                })
                .catch(error => {
                    console.error('确认收货失败:', error);
                    alert('确认收货失败，请稍后重试');
                });
        }
    }

    // 其他订单操作函数（仅定义，实际需实现）
    function viewOrderDetail(orderId) {
        console.log(orderId)
        window.location.href = `./orderDetail.html?orderId=${orderId}`;
    }

    function remindShip(orderId) {
        alert(`已发送提醒发货通知，订单ID：${orderId}`);
    }

    function viewLogistics(orderId) {
        alert(`查看订单${orderId}的物流信息`);
    }

    function gotoComment(orderId) {
        window.location.href = `/comment.html?orderId=${orderId}`;
    }

    function viewComment(orderId) {
        alert(`查看订单${orderId}的评价`);
    }

    function deleteOrder(orderId) {
        if (confirm('确定要删除该订单吗？删除后不可恢复')) {
            axios.delete(`http://localhost:8080/orders/${orderId}`)
                .then(() => {
                    alert('订单已删除');
                    fetchOrders();
                })
                .catch(error => {
                    console.error('删除订单失败:', error);
                    alert('删除订单失败，请稍后重试');
                });
        }
    }

    // Vue实例（保持与用户中心页面一致的登录状态管理）
    new Vue({
        el: "#app",
        created() {
            this.user = util.store.get("user-info");
            if (!util.isLogin()) {
                util.store.set("return-url", location.href);
                location.href = "login.html";
            }
        }
    });
</script>
</body>
</html>